package com.tepth.vehiclemaintenance.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.tools.bleNfc.NFCInterface;
import com.tepth.vehiclemaintenance.tools.bleNfc.NFCManger;

import java.util.Vector;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by zhangyu on 2017/3/29.
 */

public class NFCListActivity extends AppCompatActivity implements NFCInterface {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.list_view)
    ListView listView;
    @BindView(R.id.tv_device)
    TextView tvCurrentDevice;
    @BindView(R.id.layout_progress)
    LinearLayout layoutProgress;
    private Unbinder unbinder;
    private static final int REQUEST_CODE_LOCATION = 2;
    private Handler mHandler = new Handler();
    private ArrayAdapter<String> adapter;
    Vector<String> mNfcList = new Vector<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_list);
        unbinder = ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tvTitle.setText(R.string.nfc_list);

        //动态权限申请
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE_LOCATION);
        } else {
            setData();
        }

    }

    private void setData() {
        String address = SPUtils.getString(this, SpKey.KEY_NFC_BIND_MAC, getString(R.string.unbind_device));
        tvCurrentDevice.setText(address);
        adapter = new ArrayAdapter<>(this, R.layout.item_text, mNfcList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String mac = adapter.getItem(position);
                tvCurrentDevice.setText(mac);
                SPUtils.putString(NFCListActivity.this, SpKey.KEY_NFC_BIND_MAC, mac);
                finish();
            }
        });
        NFCManger.interruptDevice();
        NFCManger.startScanAndGetDevicedList(this, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        NFCManger.setStopGetDevicedList(true);
        NFCManger.stopSearchCard();
        NFCManger.interruptDevice();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_LOCATION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    setData();
                } else {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void searchDevice() {

    }

    @Override
    public void connectionDevice() {

    }

    @Override
    public void successConnectionDevice() {

    }

    @Override
    public void searchCard() {

    }

    @Override
    public void successCard(byte[] msgBuffer) {

    }

    @Override
    public void errorCard() {

    }

    @Override
    public void stopSearchCard() {

    }

    @Override
    public void updateDeviceList(final Vector<String> nfcList) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (nfcList != null && !nfcList.isEmpty()) {
                    listView.setVisibility(View.VISIBLE);
                    layoutProgress.setVisibility(View.GONE);
                    mNfcList.clear();
                    mNfcList.addAll(nfcList);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

}
